<?php

declare (strict_types=1);

namespace App\Model;

use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * @property int $id
 * @property int $uid
 * @property string $amount
 * @property string $currency
 * @property int $create_time
 * @property int $update_time
 */
class Balance extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'balance';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'uid' => 'integer', 'create_time' => 'integer', 'update_time' => 'integer'];


    /**
     * 账变记录
     * @param $uid 用户id
     * @param $amount 金额
     * @param $add 1 增加 0 减少
     * @param $type 账变主类型
     * @param $suffix 账变后缀类型
     * @param $association 管理数据
     * @param string $description
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function balanceLog($uid, $amount, $add, $type, $suffix, $association, $description = '')
    {

        $channel = request()->getHeaderLine('channel');
        $platform = request()->getHeaderLine('form');


        $userBalance = Balance::where(['uid' => $uid])->first();
        if (is_null($userBalance)) {
            return false;
        }

        if ($amount > $userBalance->amount) {
            return false;
        }


        try {

            $balanceLog = [
                'uid' => $uid,
                'add' => $add,
                'amount' => $amount,
                'before_amount' => $userBalance->amount,
                'currency' => $userBalance->currency,
                'description' => $description,
                'type' => $type,
                'type_suffix' => $suffix,
                'association' => json_encode($association),
                'create_time' => time(),
                'channel' => $channel,
                'platform' => $platform,
            ];

            //扣除余额、增加余额
            if ($add == 1) {
                Balance::where(['uid' => $uid])->increment('amount', $amount);
            } else {
                Balance::where(['uid' => $uid])->decrement('amount', $amount);
            }

            AccountTransaction::insert($balanceLog);

            return true;

        } catch (\Exception $e) {



            logger()->info('账变失败', $e->getMessage());
            return false;

        }


    }
}